// review.js 书评路由文件
const Router = require('koa-router')
const { 
  checkReviewExists, 
  saveReviewToDB, 
  getAllReviews,
  getNewsReviewList 
} = require('../controllers/index.js')
const router = new Router()

// 路由前缀
router.prefix('/review')

// 获取全部书评
router.get('/getAllReviews', async (ctx) => {
  try {
    const reviews = await getAllReviews()
    ctx.body = {
       code: 200,
      success: true,
      data: reviews,
    }
  } catch (error) {
    console.error('获取书评失败:', error)
    ctx.status = 500
    ctx.body = { 
      success: false, 
      message: '获取书评列表失败，请稍后重试' 
    }
  }
})

// 获取最新书评列表（前10条）
router.get('/getNewsReviewList', async (ctx) => {
  try {
    const reviews = await getNewsReviewList(10) // 获取最新10条
    
    ctx.body = {
      code: 200,
      data: reviews.length ? reviews : [],
      msg: reviews.length ? '查询成功' : '暂无书评数据'
    }
    
  } catch (error) {
    console.error('获取最新书评失败:', error)
    ctx.body = {
      code: 500,
      msg: '服务器异常，请稍后重试'
    }
  }
})

// 提交新书评（仿照文章生成逻辑）
router.post('/submitReview', async (ctx) => {
  const { bookTitle, content, rating, author } = ctx.request.body
  
  try {
    // 1. 检查重复书评
    const isExist = await checkReviewExists(bookTitle, author)
    if(isExist) {
      ctx.body = { 
        success: false, 
        message: '您已提交过该书籍的书评' 
      }
      return
    }

    // 2. 保存到数据库
    const reviewId = await saveReviewToDB({
      bookTitle,
      content,
      rating,
      author
    })

    // 3. 返回成功响应
    ctx.body = {
      success: true,
      data: {
        id: reviewId,
        bookTitle,
        rating
      },
      message: '书评提交成功'
    }

  } catch (error) {
    console.error('提交书评失败:', error)
    ctx.status = 500
    ctx.body = { 
      success: false, 
      message: '书评提交失败，请检查后重试' 
    }
  }
})

module.exports = {
  reviewRouter: router
}